import requests
import json
import re
from time import sleep

API_KEY = "90mGcXXXnmGgnRbleg5GXxK2"
SECRET_KEY = "8WNvBUU43eXiiA2O2RRvVBFmW1z5HgZv"


def main():
    val = '猫'123
    task_id = image_generate(val)
    print(task_id)
    sleep(10)
    url = "https://aip.baidubce.com/rpc/2.0/ernievilg/v1/getImg?access_token=" + get_access_token()
    payload = json.dumps({
        "taskId": task_id
    })
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    print("12345"+response.text)
    # 解析JSON数据
    parsed_data = json.loads(response.text)

    # 提取 "img" 和 "imgUrls" 字段的值
    img_url = parsed_data["data"]["img"]
    img_urls = [item["image"] for item in parsed_data["data"]["imgUrls"]]

    print("img:", img_url)
    print("imgUrls:", img_urls)
    return img_urls


def image_generate(val):
    url = "https://aip.baidubce.com/rpc/2.0/ernievilg/v1/txt2img?access_token=" + get_access_token()
    print("打印函数"+get_access_token())

    payload = json.dumps({
        "text": val,
        "resolution": "1024*1024",
        "style": "写实风格"
    })
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    print(response.text)
    task_id = ''
    data = response.text
    pattern = r'"taskId":(\d+)'
    match = re.search(pattern, data)

    if match:
        task_id = match.group(1)
        print(task_id)
    else:
        print("未找到taskId")
    return task_id


def get_access_token():
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": "90mGcXXXnmGgnRbleg5GXxK2", "client_secret": "8WNvBUU43eXiiA2O2RRvVBFmW1z5HgZv"}
    print(str(requests.post(url, params=params).json().get("access_token")))
    return str(requests.post(url, params=params).json().get("access_token"))


if __name__ == '__main__':
    main()
